package cn.shentianlan.service.impl;

import cn.shentianlan.dao.UserDao;
import cn.shentianlan.domain.User;
import cn.shentianlan.domain.UserTable;
import cn.shentianlan.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;


    @Override
    public int getUserNumber() {
        return userDao.getUserNumber();
    }

    @Override
    public void addUser(User user) {
        userDao.insertUser(user);
    }

    @Override
    public User findUserById(String gd_id) {
        return userDao.selectUserById(gd_id);
    }

    @Override
    public User findUser(String gd_id, String gd_password) {
        return  userDao.selectUser(gd_id,gd_password);
    }

    /**
     * 获取表单数据
     * @param start 开始栏数
     * @param length 需要显示的数据量
     * @param draw 请求次数
     * @param searchValue 搜索的值
     * @return userTable
     */
    @Override
    public UserTable showUser(int start, int length,int draw,String searchValue) {
        List<User> data = null;
        UserTable userTable = new UserTable();
        int totalPages = userDao.queryUserCount();

        //确保表数据不为空
        if (totalPages==0){
            User user = new User();
            user.setGd_id("21321312321");
            user.setGd_username("admin");
            user.setGd_identity("Manager");
            user.setGd_email("111111@qq.com");
            user.setGd_phone("13945678912");
            user.setGd_password("admin");
            userDao.insertUser(user);
        }


        if (searchValue!=null&& searchValue.length()!=0){
            data = userDao.selectUserBySearch(searchValue,length,start);
            int recordsFiltered = userDao.queryUserCountBySearch(searchValue);
            userTable.setRecordsFiltered(recordsFiltered);
        }else {
            data = userDao.selectUsers(start,length);
            userTable.setRecordsFiltered(totalPages);
        }

        userTable.setData(data);
        userTable.setRecordsTotal(totalPages);
        userTable.setDraw(draw);

        return userTable;
    }

    @Override
    public boolean deleteUser(String gd_id) {
        try{
            userDao.deleteUserById(gd_id);
            return true;
        }catch (Exception e){
            //将异常信息打印到控制台上
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }


}
